import threading

#from Bases import BaseObject

class Clock(object):
    '''
    :Parameters:
        granularity : float, stepsize in seconds
        period : float, total runtime in seconds
        loop : bool
        event_info : 
        
    '''
    def __init__(self, **kwargs):
        #super(Clock, self).__init__(**kwargs)
        self.granularity = kwargs.get('granularity', 0.1)
        self.period = kwargs.get('period', 1.0)
        self.looping = kwargs.get('loop', False)
        controllers = kwargs.get('controllers', [])
        self.timer = None
        self.controllers = set()
        for c in controllers:
            self.add_controller(c)
    def start(self):
        self.stop()
        self.current_time = 0.0
        self.timer = RepeatTimer(interval=self.granularity, callback=self.on_interval)
    def stop(self):
        if self.timer is not None:
            self.timer.stop()
        self.timer = None
    def add_controller(self, controller):
        self.controllers.add(controller)
    def do_callbacks(self):
        for c in self.controllers:
            c.on_interval(self.current_time)
    def on_interval(self):
        self.current_time += self.granularity
        self.do_callbacks()
        if self.current_time >= self.period:
            self.stop()
            if self.looping:
                self.start()
        print self.current_time
        
class RepeatTimer(object):
    def __init__(self, **kwargs):
        self.interval = kwargs.get('interval')
        self.callback = kwargs.get('callback')
        self.timer = None
        self.start()
    def start(self):
        self.stop()
        self.running = True
        self.build_timer()
    def stop(self):
        self.running = False
        if self.timer is not None:
            self.timer.cancel()
            self.timer = None
    def build_timer(self):
        self.timer = threading.Timer(self.interval, self.on_interval)
        self.timer.start()
    def on_interval(self):
        if self.running:
            self.build_timer()
            self.callback()

def on_cn_callback(**kwargs):
    print kwargs

if __name__ == '__main__':
    cn = Controller(callback=on_cn_callback)
    cn.add_keyframes({1:10, 2:20, 3:30})
    cl = Clock(granularity=0.5, period=3.0)
    cl.add_controller(cn)
    cl.start()
